<template>
  <el-dialog
    title="提示"
    :visible.sync="rightsDialogoClose"
    width="50%"
    @close="clearDialogo"
  >
    <el-tree
      ref="treeRightsRef"
      :data="TreeRightsList"
      :props="TreeRightsListProps"
      show-checkbox
      node-key="id"
      default-expand-all
      :default-checked-keys="defKeys"
    ></el-tree>
    <span slot="footer" class="dialog-footer">
      <el-button @click="rightsDialogoClose = false">取 消</el-button>
      <el-button type="primary" @click="allotRights">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  name: 'RightsAddDialogo',
  props: {
    TreeRightsList: {
      type: Array,
      default() {
        return []
      },
    },
    roleId: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      rightsDialogoClose: false,
      TreeRightsListProps: {
        label: 'authName',
        children: 'children',
      },
      defKeys: [],
    }
  },
  methods: {
    //通过递归获取三级权限
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    //每次点击清空一下对话框
    clearDialogo() {
      this.defKeys = []
    },
    async allotRights() {
      const keys = [
        ...this.$refs.treeRightsRef.getCheckedKeys(),
        ...this.$refs.treeRightsRef.getHalfCheckedKeys(),
      ]

      const idStr = keys.join(',')

      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('添加权限失败')
      }
      this.$message.success('添加权限成功')
      this.$parent.$parent.$parent.getRolesList()
      this.rightsDialogoClose = false
    },
  },
}
</script>

<style lang="less" scoped>
</style>